/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License.You may obtain a copy of the License at
	http://www.mozilla.org/MPL/MPL-1.1.html
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import com.bourre.utils.SharedObjectUtils;

import fever.app.context.abstract.FileSystem;
import fever.app.context.abstract.IFileSystem;
import fever.Fever;
import fever.log.FeverDebug;
import fever.utils.StringUtil;

/**
 * Simulated filesystem using SharedObject.
 * 
 * <p>This filesystem is 100% synchron.
 * 
 * //TODO Current implementation still beta; certainly need optimization and 
 * refactoring to avoid duplicated code.
 * 
 * @author Romain Ecarnot
 */
class fever.app.context.browser.SOFilesystem extends FileSystem  implements IFileSystem
{
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private static var _instance : SOFilesystem;
	private static var _fileSystemName : String = 'SOFileSystem';
	
	private var _fileSystem : Object;
	private var _isAvailable : Boolean;
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Returns {@link SOFilesystem} instance.
	 */
	public static function getInstance() : SOFilesystem
	{
		if( _instance == undefined ) _instance = new SOFilesystem();
		return _instance;
	}
	
	/**
	 * Returns {@code true} if passed-in {@code folder} is a valid directory 
	 * on filesystem.
	 * 
	 * @param folder A fully qualified path
	 */
	public function isDirectory( folder : String ) : Boolean
	{
		if( !folder ) return false;
		
		if( folder == '/' ) return true;
		else
		{
			folder = StringUtil.trim( folder, '/' );
			var a : Array = folder.split( '/' );
			var l : Number = a.length;
			var o : Object = _fileSystem;
			for( var i : Number = 0; i < l; i++ )
			{
				if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
				else return false;
			}
			return true;
		}
	}
	
	/**
	 * Creates passed-in {@code folder} directory on filesystem.
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * @param folder A fully qualified path
	 */
	public function createDirectory( folder : String ) : Boolean
	{
		if( !folder ) return false;
		
		if( folder == '/' ) return true;
		else
		{
			folder = StringUtil.trim( folder, '/' );
			var a : Array = folder.split( '/' );
			var l : Number = a.length;
			var o : Object = _fileSystem;
			var i : Number;
			for( i = 0; i < l - 1; i++ )
			{
				if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
				else return false;
			}
			
			if( o[ a[ i ] ] == undefined ) 
			{
				o[ a[ i ] ] = new Object();
				_save();
			}
			return true;
		}
	}
	
	/**
	 * Removes passed-in {@code folder} directory from filesystem.
	 * 
	 * <p>All files / folders insides are also deleted.
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * @param folder A fully qualified path
	 */
	public function deleteDirectory( folder : String ) : Boolean
	{
		if( !folder ) return false;
		
		if( folder == '/' ) return false;
		else
		{
			folder = StringUtil.trim( folder, '/' );
			var a : Array = folder.split( '/' );
			var l : Number = a.length;
			var o : Object = _fileSystem;
			var i : Number;
			for( i = 0; i < l - 1; i++ )
			{
				if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
				else return false;
			}
			
			if( typeof( o[ a[ i ] ] )== 'object' ) 
			{
				o[ a[ i ] ] = null;
				delete o[ a[ i ] ];
				
				_save();
				return true;
			}
			else return false;
		}
	}
	
	/**
	 * Renames passed-in {@code folder} directory with new passed-in 
	 * {@code newFolderName} name.
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * @param folder A fully qualified path
	 * @param newFolderName new Folder name
	 */
	public function renameDirectory( folder : String, newName : String ) : Boolean
	{
		if( !folder || !newName ) return false;
		
		if( folder == '/' ) return false;
		else
		{
			folder = StringUtil.trim( folder, '/' );
			var a : Array = folder.split( '/' );
			var l : Number = a.length;
			var o : Object = _fileSystem;
			var i : Number;
			for( i = 0; i < l - 1; i++ )
			{
				if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
				else return false;
			}
			
			if( typeof( o[ a[ i ] ] )== 'object' ) 
			{
				var content : Object = o[ a[ i ] ]; 
				o[ a[ i ] ] = null;
				delete o[ a[ i ] ];
				
				o[ newName ] = content;
				
				_save();
				return true;
			}
			else return false;
		}
	}
	
	/**
	 * Returns {@code true} if passed-in {@code path} is a valid file 
	 * on filesystem.
	 * 
	 * @param path A fully qualified file path
	 */
	public function isFile( path : String ) : Boolean
	{
		if( !path || path == '/' ) return true;
		else
		{
			path = StringUtil.trim( path, '/' );
			var a : Array = path.split( '/' );
			var l : Number = a.length;
			var o : Object = _fileSystem;
			var i : Number;
			for( i = 0; i < l - 1; i++ )
			{
				if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
				else return false;
			}
			
			if( typeof( o[ a[ i ] ] ) == 'string' ) return true;
			else return false;
		}
	}
	
	/**
	 * Renames passed-in {@code path} file with new passed-in 
	 * {@code newName} name.
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * @param path A fully qualified file path
	 * @param newName A fully qualified file path
	 */
	public function renameFile( path : String, newName : String ) : Boolean
	{
		if( !path || path == '/' ) return false;
		 
		path = StringUtil.trim( path, '/' );
		
		var a : Array = path.split( '/' );
		var l : Number = a.length;
		var o : Object = _fileSystem;
		var i : Number;
		for( i = 0; i < l - 1; i++ )
		{
			if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
			else return null;
		}
		
		if( typeof( o[ a[ i ] ] == 'string' ) )
		{
			var data : String = o[ a[ i ] ]; 
			o[ a[ i ] ] = null;
			delete o[ a[ i ] ];
			
			o[ newName ] = data;
			_save();
		}
		return true	;
	}
	
	/**
	 * Removes passed-in {@code path} file from filesystem.
	 * 
	 * 
	 * <p>Returns {@code true} if operation ends successfully.
	 * 
	 * @param path A fully qualified file path
	 */
	public function deleteFile( path : String ) : Boolean
	{
		if( !path || path == '/' ) return false;
		 
		path = StringUtil.trim( path, '/' );
		
		var a : Array = path.split( '/' );
		var l : Number = a.length;
		var o : Object = _fileSystem;
		var i : Number;
		for( i = 0; i < l - 1; i++ )
		{
			if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
			else return null;
		}
		
		if( typeof( o[ a[ i ] ] == 'string' ) )
		{
			o[ a[ i ] ] = null;
			delete o[ a[ i ] ];
			
			_save();
		}
		return true	;
	}
	
	/** 
	 * Reads file text content.
	 * 
	 * @param path A full qualified filename
	 * 
	 * @return File content or {@code null} if application can't read file.
	 */
	public function readFile( path : String ) : String
	{
		if( !path || path == '/' ) return null;
		 
		path = StringUtil.trim( path, '/' );
		
		var a : Array = path.split( '/' );
		var l : Number = a.length;
		var o : Object = _fileSystem;
		var i : Number;
		for( i = 0; i < l - 1; i++ )
		{
			if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
			else return null;
		}
		
		if( typeof( o[ a[ i ] ] == 'string' ) ) return ( o[ a[ i ] ].toString() );
		return null;
	}
	
	/**
	 * Writes text data into file.
	 * 
	 * @param path ( optional ) A fully qualified path to the file you want to write.<br />
	 * Default use application starting directory.
	 * @param data String to write in file
	 */
	public function writeToFile( data : String, path : String ) : Boolean
	{
		if( !path || path == '/' || data == undefined ) return false;
		 
		path = StringUtil.trim( path, '/' );
		
		var a : Array = path.split( '/' );
		var l : Number = a.length;
		var o : Object = _fileSystem;
		var i : Number;
		for( i = 0; i < l - 1; i++ )
		{
			if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];
			else return false;
		}
		
		o[ a[ i ] ] = data;
		_save();
		return true;
	}
	
	/**
	 * Appends text data into file.
	 * 
	 * @param path A fully qualified path to the file you want to write.<br />
	 * Default use application starting directory.
	 * @param data String to write in file
	 */
	public function appendToFile( data : String, path : String ) : Boolean
	{
		if( StringUtil.isEndingWith( path, '/' ) || !path )
		{
			FeverDebug.ERROR( 'filename is undefined in io.appendToFile()' );
			return false;
		}
		
		var a : Array = path.split( '/' );
		var l : Number = a.length;
		
		if( l < 2 ) _fileSystem[ a[0] ] = data;
		else
		{
			var folder : Object;
			for( var i : Number = 0; i < l - 1; i++ )
			{
				folder = _fileSystem[ a[i] ] = new Object(); 
			}
			var current : String = folder[ a[l - 1] ];
			if ( !current ) current = '';
			folder[ a[ l - 1 ] ] = current += data;
		}
		
		SharedObjectUtils.saveLocal( Fever.application.name, _fileSystemName, _fileSystem );
		return true;
	}
	
	/**
	 * Returns all content of filesystem.
	 */
	public function getContent( folder : String ) : Object
	{
		if( !folder || folder == '/' ) return _fileSystem;
		else
		{
			folder = StringUtil.trim( folder, '/' );
			var a : Array = folder.split( '/' );
			var l : Number = a.length;
			var o : Object = _fileSystem;
			
			for( var i : Number = 0; i < l; i++ )
			{
				if( typeof( o[ a[ i ] ] ) == 'object' ) o = o[ a[ i ] ];	
				else return null;
			}
					
			return o;
		}
		
	}
	
	public function isAvailable() : Boolean
	{
		return _isAvailable;
	}
	
	/**
	 * Returns user "temporary" directory  from current system.
	 */
	public function getTempDirectory() : String 
	{
		return '.tmp';
	}

	/**
	 * Returns current application path from current system.
	 */
	public function getAppDirectory() : String 
	{
		return '/';
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	/**
	 * Constructor
	 */
	private function SOFilesystem()
	{
		FeverDebug.WARN( 'SO FileSsytem engaged' );
		
		var so : SharedObject = SharedObject.getLocal( 'savedData' );
		if( so == null )  _isAvailable = false;
		else
		{
			var r = so.flush( 1 );
			if( r == 'pending' ) _isAvailable = true;
			else _isAvailable = r;
		}
		
		_retreiveFilesystem();
	}
	
	private function _retreiveFilesystem() : Void
	{
		_fileSystem = SharedObjectUtils.loadLocal( Fever.application.name, _fileSystemName );
			
		if( _fileSystem == undefined ) 
		{
			_fileSystem = new Object();
			SharedObjectUtils.saveLocal( Fever.application.name, _fileSystemName, _fileSystem );
		}	
	}
	
	private function _save() : Void
	{
		SharedObjectUtils.saveLocal( Fever.application.name, _fileSystemName, _fileSystem );
	}
}